import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

// 请求实例
const service = axios.create({
  baseURL: '/api',
  // withCredentials: true, // send cookies 跨域请求发送cookie
  timeout: 20000 // 请求超时时间
})

// 请求拦截
service.interceptors.request.use(
  (config) => {
    // 添加token
    if (store.getters.token) {
      config.headers['Authorization'] = JSON.parse(getToken())
    }

    // if (config.url.match(/^\/application\//)) {
    //   config.baseURL = '/login'
    // }
    if (config.url?.indexOf('/v7') != -1) {
      config.baseURL = '/weatherApi'
    }
    //页面跳转取消上一个页面请求
    config.cancelToken = new axios.CancelToken((cancel) => {
      store.commit('axios/add_AxiosPromiseArr', { cancel })
    })
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data
    // if (res.flag == false) {
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    return res
    // }
  },
  (error) => {
    return Promise.reject(error)
  }
)
export default service
